package com.atguigu.flinkWaterMark;


import com.atguigu.been.WaterSensor;
import org.apache.flink.api.common.eventtime.*;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

public class Window_EventTime_Tumbling__punctuated {
    public static void main(String[] args) throws Exception {
        //1.流的执行环境
        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment();
        senv.setParallelism(1);

        //2.获取数据
        DataStreamSource<String> streamSource = senv.socketTextStream("hadoop102", 9999);

        //3.对数据进行处理，封装成WaterSensor
        SingleOutputStreamOperator<WaterSensor> waterSensorDStream = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });
        //todo 自定义间歇性WatermarkStrategy
        SingleOutputStreamOperator<WaterSensor> watermarks = waterSensorDStream.assignTimestampsAndWatermarks(
                //生成自定义的watermark
                new WatermarkStrategy<WaterSensor>() {
                    @Override
                    public WatermarkGenerator<WaterSensor> createWatermarkGenerator(WatermarkGeneratorSupplier.Context context) {
                        return new Myperiod(2000L);
                    }
                }.withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                    @Override
                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                        return element.getTs()*1000L;//提取数据的时间戳
                    }
                })
        );
        KeyedStream<WaterSensor, String> keyedStream = watermarks.keyBy(WaterSensor::getId);
        WindowedStream<WaterSensor, String, TimeWindow> window = keyedStream.window(TumblingEventTimeWindows.of(Time.seconds(5))); //窗口时间
        window.process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
            @Override
            public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                String msg = "当前key: " + s
                        + "窗口: [" + context.window().getStart() / 1000 + "," + context.window().getEnd()/1000 + ") 一共有 "
                        + elements.spliterator().estimateSize() + "条数据 ";
                out.collect(msg);
            }
        }).print();


        senv.execute();
    }
    //TODO   自定义间歇性的Watermark生成器
    public static class Myperiod implements WatermarkGenerator<WaterSensor>{
        //最大时间戳
        private Long maxTs;

        //最大延迟时间
        private Long maxDelay;

        public Myperiod( Long maxDelay) {
            this.maxDelay = maxDelay;
            this.maxTs =Long.MIN_VALUE+ this.maxDelay + 1;

        }
        //当数据来的时候调用---间歇性
        // 获取当前数据中最大的时间戳并赋值
        @Override
        public void onEvent(WaterSensor event, long eventTimestamp, WatermarkOutput output) {
//            maxTs = Math.max(eventTimestamp,maxTs);
            System.out.println("生成Watermark");
            maxTs = Math.max(eventTimestamp, maxTs);
            output.emitWatermark(new Watermark(maxTs-maxDelay-1));
        }

        @Override
        public void onPeriodicEmit(WatermarkOutput output) {
//            output.emitWatermark(new Watermark(maxTs-maxDelay-1));


        }
    }
}
